//
//  OnlineDetailViewController.m
//  XiXi
//
//  Created by HawkingWang on 16/9/30.
//  Copyright © 2016年 xi-xi.cc. All rights reserved.
//

#import "OnlineDetailViewController.h"

#import "OnlineTableViewCell.h"//cell1
#import "OnlineDetailTitleTableViewCell.h"//cell2
#import "OnlineDetailDataTableViewCell.h"//cell3

#import "OnlineDetailModel.h"//检票信息Model
#import "OperaDataModel.h"//检票数据Model

@interface OnlineDetailViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation OnlineDetailViewController
{
    NSUserDefaults *_defaults;
    
    NSMutableArray *_operaSchduleArray;//检票信息array
    
    NSMutableArray *_operaDataArray;//检票数据Array
}

 static NSString *const OnlineTableViewCellID = @"OnlineTableViewCell";
 static NSString *const OnlineDetailTitleTableViewCellID = @"OnlineDetailTitleTableViewCell";
 static NSString *const OnlineDetailDataTableViewCellID = @"OnlineDetailDataTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _defaults = [NSUserDefaults standardUserDefaults];
    
    [self setNav];
    
    //注册TableView
    [self registerTableView];
    
    [SVProgressHUD show];
    [self requestOperaSchdule];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestOperaSchdule];
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    _model = nil;
    [_operaSchduleArray removeAllObjects];
    [_tableView reloadData];
}

- (void)setNav{
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    nav.backgroundColor = RGBCOLOR(34, 36, 45);
    [self.view addSubview:nav];
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 64) / 2, 27, 64, 30)];
    logo.image = [UIImage imageNamed:@"logo"];
    [self.view addSubview:logo];
    
    //渐变View
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 4)];
    UIColor *color1 = RGBCOLOR(33, 171, 246);
    UIColor *color2 = RGBCOLOR(247, 38, 38);
    CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
    gradientLayer.colors = @[(__bridge id)color1.CGColor,(__bridge id)color2.CGColor];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);
    gradientLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, 4);
    [view.layer insertSublayer:gradientLayer atIndex:0];
    [self.view addSubview:view];
    
    UIButton *close = [UIButton buttonWithType:UIButtonTypeCustom];
    close.frame = CGRectMake(6.3, 21.8, 40, 40);
    [close addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:close];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
    image.image = [UIImage imageNamed:@"off"];
    [close addSubview:image];
}
- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)registerTableView{
     [self.tableView registerNib:[UINib nibWithNibName:@"OnlineTableViewCell" bundle:nil] forCellReuseIdentifier:OnlineTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"OnlineDetailTitleTableViewCell" bundle:nil] forCellReuseIdentifier:OnlineDetailTitleTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"OnlineDetailDataTableViewCell" bundle:nil] forCellReuseIdentifier:OnlineDetailDataTableViewCellID];
}

#pragma mark === tableViewDelegate ===
//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return _operaSchduleArray.count;
    }else return 1;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 145;
    }else if (indexPath.section == 1){
        return 50;
    }else return 75;
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        OnlineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OnlineTableViewCellID];
        [cell loadData:_model];
        cell.image.backgroundColor = [UIColor blackColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    else if (indexPath.section == 1){
        OnlineDetailTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OnlineDetailTitleTableViewCellID];
        cell.detail.text = [NSString stringWithFormat:@"剧目开演前%@分钟可进行检票数据准备", [[NSUserDefaults standardUserDefaults] objectForKey:StopSale]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    else{
        OnlineDetailDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OnlineDetailDataTableViewCellID];
        OnlineDetailModel *model = _operaSchduleArray[indexPath.row];
        [cell loadData:model];
        cell.dataBtn.layer.borderColor = RGBCOLOR(90, 158, 252).CGColor;
        [cell.dataBtn setTitleColor:RGBCOLOR(90, 158, 252) forState:UIControlStateNormal];
        if ([model.could_check isEqualToString:@"0"]) {
            cell.dataBtn.layer.borderColor = RGBCOLOR(199, 195, 217).CGColor;
            [cell.dataBtn setTitleColor:RGBCOLOR(199, 195, 217) forState:UIControlStateNormal];
            cell.dataBtn.userInteractionEnabled = NO;
        }
        cell.dataBtnClick = ^(){
            DLog(@"准备检票数据");
            //如果已经下载过提示是否覆盖
            if ([_defaults objectForKey:[NSString stringWithFormat:@"%@%@", OperaDataSave, model.unique_id]]) {
                [self setupAlertController:model.unique_id];
            }
            [SVProgressHUD show];
            [self readyForData:model.unique_id];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

//设置弹出提示语
- (void)setupAlertController:(NSString *)unique_id{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"该场次数据已下载,是否覆盖?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"覆盖" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];
        [self readyForData:unique_id];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    [alert addAction:cancle];
    
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark === 网络请求剧目场次详情 ===
- (void)requestOperaSchdule{
    NSDictionary *para = @{
                           @"id" : _model._id,
                           @"end" : @"1"
                           };
    [NetWorkManager requestWithType:0 withMethodName:OperaSchdule withParaments:para withSuccessBlock:^(NSDictionary *object) {
//        DLog(@"%@", object);
        if (object[@"total"] > 0 || ![object[@"total"] isKindOfClass:[NSNull class]]) {
            if (!_operaSchduleArray) {
                _operaSchduleArray = [NSMutableArray array];
            }else [_operaSchduleArray removeAllObjects];
            
            for (NSDictionary *dic in object[@"items"]) {
                OnlineDetailModel *model = [OnlineDetailModel initWithDic:dic];
                [_operaSchduleArray addObject:model];
            }
            [_tableView reloadData];
            [SVProgressHUD dismiss];
            [_tableView.mj_header endRefreshing];
        }
    } withFailureBlock:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });

    } progress:nil];
}

#pragma mark === 准备检票数据 ===
- (void)readyForData:(NSString *)unique_id{
    NSDictionary *para = @{
                           @"id" : unique_id
                           };
    [NetWorkManager requestWithType:0 withMethodName:OperaData withParaments:para withSuccessBlock:^(NSDictionary *object) {
//        DLog(@"%@", object);
        if (object[@"total"] > 0 || ![object[@"total"] isKindOfClass:[NSNull class]]) {
            if (!_operaDataArray) {
                _operaDataArray = [NSMutableArray array];
            }else [_operaDataArray removeAllObjects];
            
            for (NSDictionary *dic in object[@"lists"]) {
                [_operaDataArray addObject:dic];
            }
            NSString *key = [NSString stringWithFormat:@"%@%@", OperaDataSave, unique_id];
            if ([_defaults objectForKey:key]) {
                [_defaults removeObjectForKey:key];
            }
            [_defaults setObject:_operaDataArray forKey:key];
            //将下载的场次保存到本地
            if ([_defaults objectForKey:OperaDataSave]) {
                NSMutableArray *arr = [_defaults objectForKey:OperaDataSave];
                int flag = 0;
                for (NSString *str in arr) {
                    if ([str isEqualToString:key]) {
                        flag = 1;
                        break;
                    }
                }
                //第一次下载该场次
                if (flag == 0) {
                    [arr addObject:key];
                    [_defaults removeObjectForKey:OperaDataSave];
                    [_defaults setObject:arr forKey:key];
                }
            }
            //第一次下载检票信息
            else{
                NSMutableArray *arr = [NSMutableArray array];
                [arr addObject:key];
                [_defaults setObject:arr forKey:OperaDataSave];
            }
            DLog(@"%@", [_defaults objectForKey:OperaDataSave]);
//            DLog(@"$$$$%@", [_defaults objectForKey:key]);
            [_tableView reloadData];
            [SVProgressHUD dismiss];
        }
    } withFailureBlock:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } progress:nil];

}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,68, SCREEN_WIDTH, SCREEN_HEIGHT - 68)style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
